package dao

import (
	"encoding/json"
	"fmt"
	"go.uber.org/zap"
	"homepage_srv/model"
	"log"
	"math/rand"
	model3 "order_srv/model"
	"order_srv/order"
	MQ "smart-health-platforms/inits"
	"smart-health-platforms/pkg"
	"time"
	model2 "user_srv/model"
)

//// 扣减库存
//func DelGoodsStock(goodsId, skuId, status int) bool {
//	key := fmt.Sprintf("goods_stock:%d:%d", goodsId, skuId)
//	for i := 0; i < status; i++ {
//		_, err := config.Rdb.LPop(config.Ctx, key).Result()
//		if err != nil {
//			return false
//		}
//	}
//	return true
//}

func CreateOrder(in *order.OrderCreateRequest) (*model3.Order, error) {
	var goodSku model.GoodSku
	var user model2.Users
	err := user.GetUserInfoById(int(in.UserId))
	if err != nil {
		pkg.Warn("获取用户失败")
		return nil, fmt.Errorf("获取用户失败:%w", err)
	}
	if user.Id == 0 {
		pkg.Warn("用户不存在,创建订单失败")
		return nil, fmt.Errorf("用户不存在,创建订单失败:%w", err)
	}
	err = goodSku.GetByGoodId(int(in.GoodSkuId))
	if err != nil {
		pkg.Warn("获取商品失败")
		return nil, fmt.Errorf("获取商品失败:%w", err)
	}
	if goodSku.Id == 0 {
		pkg.Warn("商品不存在")
		return nil, fmt.Errorf("商品不存在:%w", err)
	}

	if goodSku.Stock < in.TotalNum {
		pkg.Warn("商品库存不足")
		return nil, fmt.Errorf("商品库存不足:%w", err)
	}
	////扣减虚拟库存
	//if !DelGoodsStock(int(goodSku.GoodId), int(goodSku.Id), int(in.TotalNum)) {
	//	pkg.Warn("扣减虚拟库存失败")
	//	return nil, fmt.Errorf("扣减库存失败:%w", err)
	//}

	orders := &model3.Order{
		OrderSn:    "JD" + time.Now().Format("20060102150405") + fmt.Sprintf("%06d", rand.Intn(1_000_000)),
		UserId:     in.UserId,
		GoodskuId:  int32(in.GoodSkuId),
		AddressId:  int32(in.AddressId),
		RealName:   in.RealName,
		UserPhone:  in.UserPhone,
		TotalNum:   in.TotalNum,
		TotalPrice: goodSku.Price * float64(in.TotalNum),
		PayType:    in.PayType,
	}

	rabbitmq := MQ.NewRabbitMQSimple("" +
		"2301a")

	// 发送消息
	marshal, _ := json.Marshal(orders)
	msg, _ := rabbitmq.PublishSimple(marshal)
	log.Println("消息发送成功", msg)

	pkg.Info("订单创建成功", zap.Any("order", orders))

	return orders, nil
}
